#ifndef KC1110_2_RTE_RETAIN_STM32_H
#define KC1110_2_RTE_RETAIN_STM32_H

#include "plc_rte.h"
#include"hwboard.h"
#include "mcu.h"


class retain_stm32 : public mem_block {
public:
    retain_stm32(uint32_t ba, uint32_t bb, uint32_t retain_size) {
        this->retain_size = retain_size;
        adr[0] = ba;
        adr[1] = bb;
    }

    void begin(const char *, int) override {
        //
    }

    void Remove(int i) override {
        erasePage(adr[i], retain_size / 2048);
    }

    void Write(unsigned char i, unsigned int i2, void *pVoid, unsigned int len) override {
        writeFlash(adr[i] + i2, (const char *) pVoid, len);
    }

    int Read(u8 block, unsigned int i, unsigned int i1, void *pVoid) override {
        memcpy(pVoid, (const void *) (adr[block] + i), i1);
        return i1;
    }

    int Shutdown() override {
        return 0;
    }

#ifndef PLC

    int begin(byte *name, byte name_sz, uint32_t start_address, uint32_t data_len) override {
//        logger.debug("retain_stm32::begin form block 0x%x ,size=%d", APP_BLOCK_START, data_len);
        erasePage(APP_BLOCK_START, APP_BLOCK_NRS);
        a_size = data_len;
        pos = 0;
        return FLASH_BLOCK_SIZE;
    }

    int begin_read(byte *name, byte name_sz, uint32_t start_address, uint32_t data_len) override {
//        logger.debug("retain_stm32::begin_read form 0x%x ,size=%d", APP_BLOCK_START, data_len);
        pos = 0;
        return FLASH_BLOCK_SIZE;
    }

    int Write(byte *buf, int len) override {
//        if ((pos + len) > a_size) {
//            logger.error("size error ,size=%d,pos=%d,len=%d", a_size, pos, len);
//        }
        if (writeFlash(APP_START + pos, (const char *) buf, len) >= 0) {
            pos += len;
            return 0;
        }
        return -1;
    }

#endif

    const char *name() final {
        return "stm32";
    }

private:
    uint32_t adr[2]{};
    uint32_t retain_size;
    uint32_t pos, a_size;
};

#endif // KC1110_2_RTE_RETAIN_STM32_H
